import { map } from 'lodash'
import React, { useEffect, useState, useRef } from 'react'
import { inject, observer } from 'mobx-react'
import ClipboardJS from 'clipboard'

import common from '../../store/common'
import scss from './styles/log.module.scss'
import Row from '../common/row'

const spanHeight = 22

const Log = ({ visible }) => {
  const [eventLog, setEventLog] = useState([])

  const ref = useRef()

  useEffect(() => {
    setEventLog(common.eventLog)
  }, [common.eventLog])

  function copyLog() {
    const clipboard = new ClipboardJS('#copyBtn', {
      text: () => {
        return ref.current.innerText
      },
    })
    clipboard.on('success', (e) => {
      console.log('复制成功')
    })
    clipboard.on('error', (e) => {
      console.log(e)
    })
  }

  return (
    <div className={scss['log-wrap']} style={{ display: visible ? 'flex' : 'none' }}>
      <Row style={{ height: 'calc(100% - 34px)' }}>
        <div className={scss.log} ref={ref}>
          {map(eventLog, (val, k) => {
            return (
              <span key={k} style={{ height: spanHeight }}>
                {val}
              </span>
            )
          })}
        </div>
      </Row>
      <div className={scss['btn-wrap']}>
        <div id="copyBtn" className={scss['btn']} style={{ marginRight: 10 }} onClick={copyLog}>
          复制
        </div>
        <div className={scss['btn']} onClick={() => common.setEventLog([], 'reset')}>
          清空
        </div>
      </div>
    </div>
  )
}

export default inject('store')(observer(Log))
